package server

import (
	v1 "traceid-test2/api/helloworld/v1"
	"traceid-test2/internal/conf"
	"traceid-test2/internal/service"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/logging"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/transport/http"
)

// // https://github.com/go-kratos/kratos/blob/7f835db398c9d0332e69b81bad4c652b4b45ae2e/examples/traces/app/message/main.go#L38
// // 首先调用otel 库方法，得到一个 TracerProvider
// func tracerProvider(logger log.Logger) (*tracesdk.TracerProvider, error) {
// 	// examples/traces 中使用的是 jaeger，其他方式可以查看 opentelemetry 官方示例
// 	// exp, err := jaeger.NewRawExporter(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(url)))
// 	// if err != nil {
// 	// 	return nil, err
// 	// }
// 	exporter, err := stdouttrace.New(stdouttrace.WithWriter(log.NewWriter(logger)))
// 	if err != nil {
// 		log.Fatal(err)
// 	}
// 	// tp := tracesdk.NewTracerProvider( //自定义一个tracer
// 	// 	tracesdk.WithBatcher(exporter),
// 	// 	tracesdk.WithResource(resource.NewSchemaless(
// 	// 		semconv.ServiceNameKey.String("测试")),
// 	// 	),
// 	// )
// 	tp := tracesdk.NewTracerProvider(
// 		tracesdk.WithSampler(tracesdk.AlwaysSample()),
// 		// 设置 Batcher，注册jaeger导出程序
// 		tracesdk.WithBatcher(exporter),
// 		// 记录一些默认信息
// 		tracesdk.WithResource(resource.NewSchemaless(
// 			semconv.ServiceNameKey.String("fuwumingc"),
// 			attribute.String("environment", "development"),
// 			attribute.Int64("ID", 1),
// 		)),
// 	)
// 	return tp, nil
// }

// NewHTTPServer new an HTTP server.
func NewHTTPServer(c *conf.Server, greeter *service.GreeterService, logger log.Logger) *http.Server {
	// tp, _ := tracerProvider(logger)
	var opts = []http.ServerOption{
		http.Middleware(
			// tracing.Server(
			// 	tracing.WithTracerProvider(tp), //定义提供者
			// 	tracing.WithPropagator(
			// 		propagation.NewCompositeTextMapPropagator(propagation.Baggage{}, propagation.TraceContext{}), //定义传播者
			// 	),
			// ),

			recovery.Recovery(),
			tracing.Server(),
			logging.Server(logger), //这个放在下面就会有traceid了
		),
	}
	if c.Http.Network != "" {
		opts = append(opts, http.Network(c.Http.Network))
	}
	if c.Http.Addr != "" {
		opts = append(opts, http.Address(c.Http.Addr))
	}
	if c.Http.Timeout != nil {
		opts = append(opts, http.Timeout(c.Http.Timeout.AsDuration()))
	}
	srv := http.NewServer(opts...)
	v1.RegisterGreeterHTTPServer(srv, greeter)
	return srv
}
